//#include <head.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
#include <stdlib.h>
#include <stddef.h>
#include <ctype.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <signal.h>

#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/un.h>

#define DEFAULT_PORT (9000)

#define LOG_TAG "[net server]"
#define log_xxx(format, arg...)	do { printf(LOG_TAG"[%d:%s] "format"\n",__LINE__, __func__, ##arg);}\
									while (0)
#define CLEAR_ARRAY(a) memset(a,0,sizeof(a))
#define CLEAR_MEM(addr,len) memset(addr,0,len)

void fn(char *p);

int main(int argc, char **argv)
{
    char buf[100];
    
    int on = 1;

    uint16_t port =DEFAULT_PORT;
    int serversocket =  socket(AF_INET,SOCK_STREAM,0);
    if(serversocket ==-1){
        printf("socket err:%s\n",strerror(errno));
        return -1;
    }
    if(argc ==2){
        port =atoi(argv[1]);
    }
    struct sockaddr_in  addr ;
    memset(&addr,0,sizeof(addr));
    addr.sin_family =AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    int r;	
    // int r=  inet_pton(AF_INET,"127.0.0.1",&(addr.sin_addr.s_addr));
    // if(r ==0){
    //     sys_error("inet_pton");
    // }
    setsockopt(serversocket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    r= bind(serversocket,(struct sockaddr*)&addr,sizeof(addr));
    if(r == -1){
        printf("bind err:%s\n",strerror(errno));
    }
    listen(serversocket,10);
    struct sockaddr_in  client;
    socklen_t  l =sizeof(client);
  
    while (1)
    {
        memset(&client, 0, sizeof(client));
        int cfd = accept(serversocket, (struct sockaddr *)&client, &l);
        CLEAR_ARRAY(buf);
        printf("New connection from IP:%s,port:%d\n",inet_ntop(AF_INET,&(client.sin_addr),buf,sizeof(buf)),ntohs(client.sin_port));
        while (1)
        {
            CLEAR_ARRAY(buf);
            for (int i = 'A'; i < 'z'; i++){
                write(cfd, &i, 1);
                sleep(5);
            }
            
            #if 0
            int len = read(cfd, buf, sizeof(buf));
            if(len ==0){
                log_xxx("client(%s:%d) disconnected!",buf,ntohs(client.sin_port));
                close(cfd);
                break;
            }
            if (len > 0)
            {
                write(STDOUT_FILENO, buf, len);
                fn(buf);
                write(cfd, buf, len);
            }
            #endif
        }
    }
    close(serversocket);
    return 0;
}
void fn(char *p)
{
    if (!p)
    {
        return;
    }
    while (*p)
    {
        *p = toupper(*p);
        p++;
    }
}
